package com.shamp.shop.basic.service.impl;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.Errors;



import com.shamp.shop.basic.dao.UserDao;
import com.shamp.shop.basic.model.User;
import com.shamp.shop.basic.service.UserService;

@Service
@Transactional
public class UserServiceImpl implements UserService {

	private static final Logger log = LoggerFactory.getLogger(UserServiceImpl.class);
	
	@Autowired
	UserDao userDao;
	@Autowired
	PasswordEncoder passwordEncoder;
	public boolean createUser(User user, String password, Errors errors) {
		validateUsername(user.getUserName(), errors);
		boolean valid = !errors.hasErrors();
		String encodePassword = passwordEncoder.encodePassword(password, null);
		
		log.info("encoded Password: "+encodePassword);
		user.setPassword(password);
		user.setConfirmPassword(password);
		if (valid) {
			System.out.println("user "+user);
			userDao.save(user);
		}
		
		return valid;
	}
	
	private void validateUsername(String username, Errors errors) {
		if (userDao.findByUserName(username) != null) {
			log.debug("Validation failed: duplicate username");
			errors.rejectValue("username", "error.duplicate", new String[] { username }, null);
		}
	}

	public Iterable<User> getUsers() {
		
		return userDao.findAll();
		
		//return null;
	}

	public List<User> getUsersByEmail(String Email) {
		// TODO Auto-generated method stub
		return null;
	}

	public User getUser(Long id) {
		// TODO Auto-generated method stub
		return null;
	}

	public void updateUser(User user) {
		// TODO Auto-generated method stub
		
	}

	public void deleteUser(Long id) {
		// TODO Auto-generated method stub
		
	}

}
